<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
    <div class="jeecg-basic-table-header__tableTitle">

      <a-button type="primary" v-if="transferShow && hasPermission('workOrder:add')" @click="handleTransfer" preIcon="ant-design:plus-outlined"> 转派</a-button>
      <a-button type="primary" v-if="takingOrdersShow" @click="handleTakingOrders" preIcon="ant-design:plus-outlined"> 接单</a-button>
      <a-button type="primary" v-if="serviceTimeShow" @click="handleServiceTime" preIcon="ant-design:plus-outlined"> 预约客户</a-button>
      <a-button type="primary" v-if="serviceRecordsShow" @click="handleServiceRecords" preIcon="ant-design:plus-outlined"> 服务记录</a-button>
      <a-button type="primary" v-if="attendanceRecordShow" @click="handleSignIn" preIcon="ant-design:plus-outlined"> 签到</a-button>
      <a-button type="primary" v-if="orderReceiptShow" @click="handleOrderReceipt" preIcon="ant-design:plus-outlined"> 回执</a-button>
      <a-button type="primary" v-if="receiptReviewShow" @click="handleReceiptReview" preIcon="ant-design:plus-outlined"> 回执审核</a-button>
      <a-button type="primary" v-if="followUpShow" @click="handleFollowUp" preIcon="ant-design:plus-outlined"> 回访</a-button>
    </div>
      <BasicForm @register="registerForm" ref="formRef"/>
  <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="安装订单" key="installationOrder" :forceRender="true">
        <InstallationOrderForm ref="installationOrderForm" :disabled="formDisabled"></InstallationOrderForm>
      </a-tab-pane>

      <a-tab-pane :tab="workOrderProcessTitle" key="workOrderProcess" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="workOrderProcess"
          :loading="workOrderProcessTable.loading"
          :columns="workOrderProcessTable.columns"
          :dataSource="workOrderProcessTable.dataSource"
          :height="340"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          />
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
  <!-- 表单区域 -->
  <TransferModal title="转派" @register="registerTransferModal" @success="handleSuccess"></TransferModal>
  <ServiceTimeModal title="修改上门服务时间" @register="registerServiceTimeModal" @success="handleSuccess"></ServiceTimeModal>
  <AttendanceRecordModal title="签到" @register="registerAttendanceRecordModal" @success="handleSuccess"></AttendanceRecordModal>
  <ServiceRecordsModal title="服务记录" @register="registerServiceRecordsModal" @success="handleSuccess"></ServiceRecordsModal>
  <FollowUpModal title="工单回访" @register="registerFollowUpModal" @success="handleSuccess"></FollowUpModal>
  <OrderReceiptModal title="工单回执" @register="registerOrderReceiptModal" @success="handleSuccess"></OrderReceiptModal>
  <ReceiptReviewModal title="审核回执" @register="registerReceiptReviewModal" @success="handleSuccess"></ReceiptReviewModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref,reactive} from 'vue';
    import {BasicModal, useModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import { JVxeTable } from '/@/components/jeecg/JVxeTable'
    import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts'
    import InstallationOrderForm from './InstallationOrderForm.vue'
    import {formSchema,workOrderProcessJVxeColumns} from '../WorkOrder.data';
    import {saveOrUpdate, queryInstallationOrder, queryWorkOrderProcess, takingOrders} from '../WorkOrder.api';
    import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils'
    import FollowUpModal from "@/views/crm/followUp/components/WorkOrderModal.vue";
    import OrderReceiptModal from "@/views/crm/orderReceipt/components/WorkOrderModal.vue";
    import TransferModal from "@/views/crm/transfer/components/TransferModal.vue";
    import ServiceRecordsModal from "@/views/crm/workServiceRecords/components/WorkOrderModal.vue";
    import ServiceTimeModal from "@/views/crm/serviceTime/components/ServiceTimeModal.vue";
    import ReceiptReviewModal from "@/views/crm/receiptReview/components/WorkOrderModal.vue";
    import AttendanceRecordModal from "@/views/crm/attendanceRecord/components/WorkOrderModal.vue";
    import { usePermission } from '/@/hooks/web/usePermission';
    const { hasPermission } = usePermission();
    //注册model
    // const [registerMaintainOrdersModal, {openModal: openMaintainOrdersModal}] = useModal();
    // const [registerInstallationOrderModal, { openModal: openInstallationOrderModal }] = useModal();
    const [registerTransferModal, { openModal: openTransferModal }] = useModal();
    const [registerServiceTimeModal, { openModal: openServiceTimeModal }] = useModal();
    const [registerAttendanceRecordModal, { openModal: openAttendanceRecordModal }] = useModal();
    const [registerServiceRecordsModal, { openModal: openServiceRecordsModal }] = useModal();
    const [registerFollowUpModal, { openModal: openFollowUpModal }] = useModal();
    const [registerOrderReceiptModal, { openModal: openOrderReceiptModal }] = useModal();
    const [registerReceiptReviewModal, { openModal: openReceiptReviewModal }] = useModal();
    let dataRecord;
    const transferShow = ref(false);
    const takingOrdersShow = ref(false);
    const serviceTimeShow = ref(false);
    const serviceRecordsShow = ref(false);
    const attendanceRecordShow = ref(false);
    const orderReceiptShow = ref(false);
    const receiptReviewShow = ref(false);
    const followUpShow = ref(false);
    let workOrderStatus;

    /**
     * 成功回调
     */
    function handleSuccess() {
      console.log("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000=",workOrderStatus);
      resetHandleSuccess();
      if(workOrderStatus==12){
        followUpShow.value=true;
      }
      if(workOrderStatus!=12 && workOrderStatus!=13) {
        transferShow.value=true;
      }
      if(workOrderStatus==17) {
        orderReceiptShow.value=true;
        serviceRecordsShow.value=true;
      } else if(workOrderStatus==9) {
        receiptReviewShow.value=true;
        serviceRecordsShow.value=true;
      } else if(workOrderStatus==16) {
        attendanceRecordShow.value=true;
      } else if(workOrderStatus==15){
        serviceTimeShow.value=true;
        serviceRecordsShow.value=true;
      } else if(workOrderStatus==3){
        takingOrdersShow.value=true;
      }
    }
    function resetHandleSuccess() {
      followUpShow.value=false;
      transferShow.value=false;
      orderReceiptShow.value=false;
      serviceRecordsShow.value=false;
      receiptReviewShow.value=false;
      attendanceRecordShow.value=false;
      serviceTimeShow.value=false;
      takingOrdersShow.value=false;
    }
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const formDisabled = ref(false);
    const refKeys = ref(['installationOrder', 'workOrderProcess', ]);
    const activeKey = ref('installationOrder');
    const installationOrderForm = ref();
    const workOrderProcess = ref();
    const tableRefs = {workOrderProcess, };
    const workOrderProcessTable = reactive({
          loading: false,
          dataSource: [],
          columns:workOrderProcessJVxeColumns
    })
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        //labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 24}
    });
     //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await reset();
        setModalProps({confirmLoading: false,showCancelBtn:data?.showFooter,showOkBtn:data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        formDisabled.value = !data?.showFooter;
		
        if (unref(isUpdate)) {
          dataRecord=data.record;
          workOrderStatus=dataRecord.workOrderStatus;
          handleSuccess();
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
             installationOrderForm.value.initFormData(queryInstallationOrder,data?.record?.id)
			 console.log("data.record==",installationOrderForm.value.getFormData());
             requestSubTableData(queryWorkOrderProcess, {id:data?.record?.id}, workOrderProcessTable)
        } else {
			data.record = {
				workOrderType: "1"
			}
			//表单赋值
            await setFieldsValue({
                ...data.record,
            });
		}
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //方法配置
    const [handleChangeTabs,handleSubmit,requestSubTableData,formRef] = useJvxeMethod(requestAddOrEdit,classifyIntoFormData,tableRefs,activeKey,refKeys,validateSubForm);

    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
	const workOrderProcessTitle = computed(() => (!unref(formDisabled) ? '' : '工单流程'));
	
    async function reset(){
      await resetFields();
      activeKey.value = 'installationOrder';
      installationOrderForm.value.resetFields();
      workOrderProcessTable.dataSource = [];
    }
    function classifyIntoFormData(allValues) {
         let main = Object.assign({}, allValues.formValue)
         return {
           ...main, // 展开
           installationOrderList: installationOrderForm.value.getFormData(),
           workOrderProcessList: allValues.tablesValue[0].tableData,
         }
       }
     //校验所有一对一子表表单
     function validateSubForm(allValues){
         return new Promise((resolve,reject)=>{
             Promise.all([
                  installationOrderForm.value.validateForm(0),
             ]).then(() => {
                 resolve(allValues)
             }).catch(e => {
                 if (e.error === VALIDATE_FAILED) {
                     // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                     activeKey.value = e.index == null ? unref(activeKey) : refKeys.value[e.index]
                 } else {
                     console.error(e)
                 }
             })
         })
     }
    //表单提交事件
    async function requestAddOrEdit(values) {
        try {
            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(values, isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
    /**
     * 转派事件
     */
    function handleTransfer() {
      console.log('dataRecorddataRecorddataRecorddataRecorddataRecorddataRecorddataRecorddataRecorddataRecord',dataRecord);
      openTransferModal(true, {
        record:dataRecord,
        isUpdate: true,
        showFooter: true,
      });
    }
    /**
     * 接单事件
     */
    function handleTakingOrders() {
      workOrderStatus=15;
      takingOrders({id: dataRecord.id}, handleSuccess);

    }
    /**
     * 服务记录事件
     */
    function handleServiceRecords() {
      openServiceRecordsModal(true, {
        record:dataRecord,
        isUpdate: false,
        showFooter: true,
      });
    }
    /**
     * 预约客户修改上门服务时间事件
     */
    function handleServiceTime() {
      workOrderStatus=16;
      openServiceTimeModal(true, {
        record:dataRecord,
        isUpdate: true,
        showFooter: true,
      });
    }
    /**
     * 签到事件
     */
    function handleSignIn() {
      workOrderStatus=17;
      openAttendanceRecordModal(true, {
        record:dataRecord,
        isUpdate: true,
        showFooter: true,
      });
    }
    /**
     * 工单回执事件
     */
    function handleOrderReceipt() {
      workOrderStatus=9;
      openOrderReceiptModal(true, {
        record:dataRecord,
        isUpdate: true,
        showFooter: true,
      });
    }
    /**
     * 审核回执事件
     */
    function handleReceiptReview() {
      workOrderStatus=12;
      openReceiptReviewModal(true, {
        record:dataRecord,
        isUpdate: true,
        showFooter: true,
      });
    }
    /**
     * 工单回访事件
     */
    function handleFollowUp() {
      workOrderStatus=13;
      openFollowUpModal(true, {
        record:dataRecord,
        isUpdate: true,
        showFooter: true,
      });
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
    :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>
